package com.lagou;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

/**
 * 手动更新数据库的utl连接，使用showtables查询数据
 * 来模拟更新zk节点数据的操作
 */
public class JdbcTest {
    static ZkClient zkClient = null;
    public static void main(String[] args) throws InterruptedException {

        String zkPath = "/lg-zkClient/dbConfig";
        // 获取zk连接
        zkClient = ZkUtils.getCon();
        // 使用自定义序列化
        zkClient.setZkSerializer(new ZkStrSerializer());
        // 创建zk节点并将常量文件中的数据库配置信息写入到zk
        ZkUtils.createNode(zkClient,zkPath);
        // 使用配置信息初始化数据库连接信息
        DataSource dataSource = DruidUtils.addConf(zkClient,zkPath);
        // 执行查询
        DruidUtils.execQuery(dataSource,zkPath);
        System.out.println("");
        Thread.sleep(4000);
        // 匿名内部类监听节点数据是否变化
        zkClient.subscribeDataChanges(zkPath, new IZkDataListener() {
            //Logger logger = LoggerFactory.getLogger(JdbcTest.class);
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
               // logger.info(s + "data is changed, new data is " + o);
                System.out.println(s + "data is changed, new data is " + o);

                // 配置信息变化，重新获取配置信息并执行查询
                DataSource dataSource = DruidUtils.addConf(zkClient,s);
                DruidUtils.execQuery(dataSource,s);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                //logger.info(s + "is deleted!!!");
                System.out.println(s + "is deleted!!!");
            }
        });

        // 手动更新zk节点里的配置信息，用来触发监听器
       zkClient.writeData(zkPath,"jdbc:mysql://centos7-1:2181/mysql?characterEncoding=UTF-8    root    12345678");
       Thread.sleep(5000);



    }
}
